using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading.Tasks;
using WCS.Infrastructure.Attr;
using WCS.Infrastructure.EFCore;
using WCS.Infrastructure.Tools;
using WCS.Service.Interface;

namespace WCS.Service.Instance
{
    [Inject]
    public class SmsService : ISmsService
    {
        private readonly IConfiguration _configuration;
        private readonly IDistributedCache _cache;

        public SmsService(IConfiguration configuration, IDistributedCache cache)
        {
            _configuration = configuration;
            _cache = cache;
        }

        /// <summary>
        /// 发送验证码短信并缓存（外部）
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public async Task<string> SendVerificationCodeAsync(string phoneNumber)
        {
            var code = Config.GenerateSecureVerificationCode();
            var result = SendSmsCode(phoneNumber, code);
            if (result.Contains("OK"))
            {
                var cacheKey = $"Sms:VerificationCode:{phoneNumber}";
                var codeBytes = Encoding.UTF8.GetBytes(code); // 字符串转byte[]
                await _cache.SetAsync(cacheKey, codeBytes, new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5)
                });
            }

            //var codeBytes = await _cache.GetAsync(cacheKey);//读取验证码
            //var code = codeBytes != null ? Encoding.UTF8.GetString(codeBytes) : null;
            return result;
        }

        /// <summary>
        /// 发送带用户名和密码的短信（外部）
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public string SendSmsPhoneAndPassword(string phoneNumber, string userName, string password)
        {
            return SendCommonSms(phoneNumber, "广州鹰游信息科技", "SMS_495000261", JsonConvert.SerializeObject(new { username = userName, password }));//SMS_485290809
        }

        /// <summary>
        /// 发送验证码短信（内部方法）
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        private string SendSmsCode(string phoneNumber, string code)
        {
            return SendCommonSms(phoneNumber, "广州鹰游信息科技", "SMS_495015252", JsonConvert.SerializeObject(new { code }));//SMS_485855008
        }

        /// <summary>
        /// 校验验证码
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<bool> VerifyCodeAsync(string phoneNumber, string code)
        {
            //校验验证码
            var cacheKey = $"Sms:VerificationCode:{phoneNumber}";
            var codeBytes = await _cache.GetAsync(cacheKey);
            var cachedCode = codeBytes != null ? Encoding.UTF8.GetString(codeBytes) : null;
            if (cachedCode == null || cachedCode != code)
            {
                // 验证码错误或已过期
                return false;
            }

            // 删除验证码缓存（防止重复使用）
            await _cache.RemoveAsync(cacheKey);

            return true;
        }

        /// <summary>
        /// 通用短信发送方法（核心）
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="signName"></param>
        /// <param name="templateCode"></param>
        /// <param name="templateParam"></param>
        /// <returns></returns>
        private string SendCommonSms(string phoneNumber, string signName, string templateCode, string templateParam)
        {
            IClientProfile profile = DefaultProfile.GetProfile(
                _configuration["Aliyun:RegionId"],
                _configuration["Aliyun:AccessKeyID"],
                _configuration["Aliyun:AccessKeySecret"]
            );
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest
            {
                Method = MethodType.POST,
                Domain = "dysmsapi.aliyuncs.com",
                Version = "2017-05-25",
                Action = "SendSms"
            };
            request.AddQueryParameters("PhoneNumbers", phoneNumber);
            request.AddQueryParameters("SignName", signName);
            request.AddQueryParameters("TemplateCode", templateCode);
            request.AddQueryParameters("TemplateParam", templateParam);

            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                return System.Text.Encoding.Default.GetString(response.HttpResponse.Content);
            }
            catch (ServerException e)
            {
                return e.ToString();
            }
            catch (ClientException e)
            {
                return e.ToString();
            }
        }
    }
}